package util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import javax.servlet.http.Part;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class UtilYun {
    //阿里云域名
    public static final String ALI_DOMAIN = "https://liualing.oss-cn-guangzhou.aliyuncs.com/";
    //地域节点
    static final String endpoint = "http://oss-cn-guangzhou.aliyuncs.com";
    //Bucket名称
    static final String bucket = "liualing";

    //阿里云AccessKey管理生成的信息,在阿里云账号里面查找该信息
    static final String accessKeyId = "LTAI5tDUGKqjzXaRwovJqepu";
    static final String accesskeySecret = "j4G2w2gHTBhARuHI4H2ZUNU3LwrQe4";

    public static Map<String, String> uploadImage(Part part) {
        //获取全名
        String fName = extractFileName(part);
        //获取带点后缀名
        String suf = suffixName(fName);
        //获取id虚拟名称
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //获取id虚拟名称+后缀名
        String xnm = uuid + suf;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accesskeySecret);

        try {
            ossClient.putObject(bucket, xnm, part.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //关闭连接
        ossClient.shutdown();

        //把数据存储到map存入到数据库
        Map<String, String> map = new HashMap<>();
        map.put("realFile", fName);
        map.put("dummyFile", xnm);
        map.put("suf", suf);
        map.put("uuid",uuid);
        return map;
    }

    public static String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String item : items) {
            if (item.trim().startsWith("filename"))
                return item.substring(item.indexOf("=") + 2, item.length() - 1);
        }
        return " ";
    }

    public static String suffixName(String fileName) {
        return fileName.substring(fileName.indexOf("."), fileName.length());
    }


}
